import os
import sys
import csv
import json
import subprocess
import shutil


script_path = os.path.dirname(os.path.abspath(__file__))
source_root_dir = script_path
print("source_root_dir:" + source_root_dir)

while not os.path.exists(os.path.join(source_root_dir, '.gn')):
    source_root_dir = os.path.abspath(source_root_dir + os.path.sep + "..")
    if source_root_dir == "/":
        print ("Cannot find source tree containning")
        sys.exit()

sys.path.append(os.path.join(source_root_dir, 'build'))

from scripts.util.file_utils import read_json_file, write_json_file, read_file # noqa: E402, E501

def write_file(output_file, content):
    file_dir = os.path.dirname(os.path.abspath(output_file))
    if not os.path.exists(file_dir):
        os.makedirs(file_dir, exist_ok=True)

    with open(output_file, 'w') as output_f:
        output_f.write(content)

def _read_csv_file(input_file):
    if not os.path.exists(input_file):
        print("file '{}' doesn't exist.".format(input_file))
        return None

    data = {}
    try:
        with open(input_file, 'r') as file_obj:
            reader = csv.reader(file_obj)
            for item in reader:
                data[item[0]] = item[1]
    except:
        print("read file '{}' failed".format(input_file))
        raise
    return data

def _parse_config(config_info_file):
    config_info = _read_csv_file(config_info_file)
    product_name = config_info['product_name']
    product_company = config_info['product_company']
    device_company = config_info['device_company']
    board = config_info['board']
    ohos_version = config_info['ohos_version']
    kernel_version = config_info['kernel_version']
    kernel_type = config_info['kernel_type']

    product_configs = {}
    product_configs['product_name'] = product_name
    product_configs['product_company'] = product_company
    product_configs['device_company'] = device_company
    product_configs['board'] = board
    product_configs['ohos_version'] = ohos_version
    product_configs['kernel_version'] = kernel_version
    product_configs['kernel_type'] = kernel_type

    return product_configs

def _make_dir(file_dir):
    if not os.path.exists(file_dir):
        os.makedirs(file_dir, exist_ok=True)

# init config.json
def _write_vendor_adapter_dir_config_json(config_json_file, product_configs):
    file_content  = "{\n"
    file_content += "    \"product_name\": \"stm32f429discovery\",\n"
    file_content += "    \"ohos_version\": \"OpenHarmony 1.1.0\",\n"
    file_content += "    \"device_company\": \"st\",\n"
    file_content += "    \"board\": \"stm32f429\",\n"
    file_content += "    \"kernel_type\": \"liteos_m\",\n"
    file_content += "    \"kernel_version\": \"\",\n"
    file_content += "    \"subsystems\": [\n"
    file_content += "      {\n"
    file_content += "        \"subsystem\": \"distributedschedule\",\n"
    file_content += "        \"components\": [\n"
    file_content += "          { \"component\": \"samgr_lite\", \"features\":[] }\n"
    file_content += "        ]\n"
    file_content += "      }\n"
    file_content += "    ],\n"
    file_content += "    \"vendor_adapter_dir\": \"//device/st/stm32f429/stm32f407_adapter\",\n"
    file_content += "    \"third_party_dir\": \"//device/st/stm32f429/liteos_m/third_party\",\n"
    file_content += "    \"product_adapter_dir\": \"//vendor/st/stm32f429/stm32f429_adapter\",\n"
    file_content += "    \"ohos_product_type\":\"\",\n"
    file_content += "    \"ohos_manufacture\":\"\",\n"
    file_content += "    \"ohos_brand\":\"\",\n"
    file_content += "    \"ohos_market_name\":\"\",\n"
    file_content += "    \"ohos_product_series\":\"\",\n"
    file_content += "    \"ohos_product_model\":\"\",\n"
    file_content += "    \"ohos_software_model\":\"\",\n"
    file_content += "    \"ohos_hardware_model\":\"\",\n"
    file_content += "    \"ohos_hardware_profile\":\"\",\n"
    file_content += "    \"ohos_serial\":\"\",\n"
    file_content += "    \"ohos_bootloader_version\":\"\",\n"
    file_content += "    \"ohos_secure_patch_level\":\"\",\n"
    file_content += "    \"ohos_abi_list\":\"\"\n"
    file_content += "}\n"
    write_file(config_json_file, file_content)

def _write_vendor_adapter_dir_Build_gn(config_json_file, product_configs):
    file_content = "group(\"stm32f429discovery\") {\n"
    file_content += "}"
    write_file(config_json_file, file_content)

def _write_device_dir_Build_gn(config_json_file, product_configs):
    file_content = "group(\"stm32f429\") {\n"
    file_content += "}"
    write_file(config_json_file, file_content)

def _write_vendor_adapter_dir_config_json(config_json_file, product_configs):
    file_content  = "{\n"
    file_content += "    \"product_name\": \"stm32f429discovery\",\n"
    file_content += "    \"ohos_version\": \"OpenHarmony 1.1.0\",\n"
    file_content += "    \"device_company\": \"st\",\n"
    file_content += "    \"board\": \"stm32f429\",\n"
    file_content += "    \"kernel_type\": \"liteos_m\",\n"
    file_content += "    \"kernel_version\": \"1.1.0\",\n"
    file_content += "    \"subsystems\": [\n"
    file_content += "      {\n"
    file_content += "        \"subsystem\": \"distributedschedule\",\n"
    file_content += "        \"components\": [\n"
    file_content += "          { \"component\": \"samgr_lite\", \"features\":[] }\n"
    file_content += "        ]\n"
    file_content += "      }\n"
    file_content += "    ],\n"
    file_content += "    \"vendor_adapter_dir\": \"//device/st/stm32f429/stm32f407_adapter\",\n"
    file_content += "    \"third_party_dir\": \"//device/st/stm32f429/liteos_m/third_party\",\n"
    file_content += "    \"product_adapter_dir\": \"//vendor/st/stm32f429/stm32f429_adapter\",\n"
    file_content += "    \"ohos_product_type\":\"\",\n"
    file_content += "    \"ohos_manufacture\":\"\",\n"
    file_content += "    \"ohos_brand\":\"\",\n"
    file_content += "    \"ohos_market_name\":\"\",\n"
    file_content += "    \"ohos_product_series\":\"\",\n"
    file_content += "    \"ohos_product_model\":\"\",\n"
    file_content += "    \"ohos_software_model\":\"\",\n"
    file_content += "    \"ohos_hardware_model\":\"\",\n"
    file_content += "    \"ohos_hardware_profile\":\"\",\n"
    file_content += "    \"ohos_serial\":\"\",\n"
    file_content += "    \"ohos_bootloader_version\":\"\",\n"
    file_content += "    \"ohos_secure_patch_level\":\"\",\n"
    file_content += "    \"ohos_abi_list\":\"\"\n"
    file_content += "}\n"
    write_file(config_json_file, file_content)

def _write_device_dir_config_gni(file, product_configs):
    file_content =  "kernel_type = \"liteos_m\"\n"
    file_content += "kernel_version = \"1.1.0\"\n"
    file_content += "board_cpu = \"cortex-m4\"\n"
    file_content += "board_arch = \"\"\n"
    file_content += "board_toolchain = \"gcc-arm-none-eabi\"\n"
    file_content += "board_toolchain_path = \"\""
    file_content += "board_toolchain_prefix = \"arm-none-eabi-\"\n"
    file_content += "board_toolchain_type = \"gcc\"\n"
    file_content += "board_cflags = []\n"
    file_content += "board_cxx_flags = board_cflags\n"
    file_content += "board_ld_flags = []\n"
    file_content += "board_include_dirs = [\n"
    file_content += "  \"${ohos_root_path}device/st/stm32f429/liteos_m/\",\n"
    file_content += "  \"${ohos_root_path}utils/native/lite/include\",\n"
    file_content += "  \"${ohos_root_path}kernel/liteos_m/kal/cmsis\",\n"
    file_content += "  \"${ohos_root_path}kernel/liteos_m/kernel/arch/arm/cortex-m4/gcc\",\n"
    file_content += "  \"${ohos_root_path}kernel/liteos_m/utils\",\n"
    file_content += "  \"${ohos_root_path}third_party/bounds_checking_function/include\",\n"
    file_content += "  \"${ohos_root_path}kernel/liteos_m/kernel/include\",\n"
    file_content += "]\n"
    file_content += "board_adapter_dir =  \"\"\n"
    file_content += "board_configed_sysroot = \"\"\n"
    file_content += "storage_type = \"\"\n"
    write_file(file, file_content)

def _write_device_dir_target_config(file, product_configs):
    shutil.copyfile(script_path + "/target_config.h" , file)

def _write_device_dir_system_config(file, product_configs):
    shutil.copyfile(script_path + "/system_config.h" , file)

def _init_config(config_info_file):
    product_configs = _parse_config(config_info_file)
    device_company = product_configs.get('device_company')
    board = product_configs.get('board')
    ohos_version = product_configs.get('ohos_version')
    kernel_version = product_configs.get('kernel_version')
    kernel_type = product_configs.get('kernel_type')
    product_name = product_configs.get('product_name')
    product_company = product_configs.get('product_company')

    base_path = os.getcwd()

    # mkdir vendor/st/stm32f429discovery
    vendor_dir = base_path + "/vendor/" + product_company + "/" + product_name
    print(vendor_dir)
    _make_dir(vendor_dir)

    # 配置 vendor/st/stm32f429discovery/config.json
    _write_vendor_adapter_dir_config_json(vendor_dir + "/config.json", product_configs)

    # 配置BUILD.gn
    _write_vendor_adapter_dir_Build_gn(vendor_dir + "/BUILD.gn", product_configs)

    # mkdir device/st/stm32f429
    device_dir = base_path + "/device/" + device_company + "/" + board
    device_kernel_dir = device_dir + "/" + "liteos_m"
    print(device_dir)
    _make_dir(device_kernel_dir)

    # 配置device/st/stm32f429/BUILD.gn
    _write_device_dir_Build_gn(device_dir + "/BUILD.gn", product_configs)

    # 配置device/st/stm32f429/liteos_m/config.gni
    _write_device_dir_config_gni(device_kernel_dir + "/config.gni", product_configs)

    # 配置device/st/stm32f429/liteos_m/target_config.h
    _write_device_dir_target_config(device_kernel_dir + "/target_config.h", product_configs)

def main():
    config_info_file = os.path.join(script_path, 'config_info.csv')
    _init_config(config_info_file)

if __name__ == '__main__':
    sys.exit(main())
